package cart

import (
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/order/rpc/orderclient"
	// "github.com/zeromicro/go-zero/core/logx"
)

// CartInfoHandler 获取购物车数据handler
type CartInfoHandler struct {
	// 合成复用Next
	Next
}

// Do 获取购物车数据
func (h *CartInfoHandler) Do(c *Context) (err error) {
	// logx.Infow("获取购物车数据...")

	page, pageSize := parse.ParsePageInfo(
		c.Req.Current,
		c.Req.PageSize,
		c.SvcCtx.Config.Query.DefaultAmount,
		c.SvcCtx.Config.Query.MaxAmount,
	)

	preload := "cartItem:Id,SkuId,ProductId,OrderId,GemPrice,RetailPrice,Quantity,Status,Favorable,Memo,PostId,InviterId"
	var prefetch *string
	filters := []string{"UserId,equalTo:" + strconv.FormatUint(c.UserId, 10)}
	if c.Req.Status != nil {
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(*c.Req.Status), 10))
	} else {
		filters = append(filters, "Status,notEqualTo:"+strconv.FormatInt(int64(globalkey.StatusDeleted), 10))
	}

	variationIdCheckedMap := make(map[uint64]struct{}) // 选中的购物车项目
	var checkedIds []string
	if c.Req.SkuIds != nil {
		if skuIds := strings.TrimSpace(*c.Req.SkuIds); len(skuIds) > 0 {
			if ids := strings.Split(skuIds, ","); len(ids) > 0 {
				for _, id := range ids {
					if i, err := strconv.ParseInt(id, 10, 64); err == nil {
						variationIdCheckedMap[uint64(i)] = struct{}{}
						checkedIds = append(checkedIds, id)
					}
				}
				c.CheckedMap = variationIdCheckedMap
			}
		}
	}
	if len(checkedIds) > 0 {
		prefetch = pointy.GetPointer(strings.Join(checkedIds, ","))
	}

	res, err := c.SvcCtx.OrderRpc.GetShoppingCart(c.Ctx, &orderclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		Prefetch:   prefetch,
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     c.Req.Sorter,
		VisitorId:  pointy.GetPointer(uint64(c.UserId)),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	c.Resp.BaseListInfo = types.BaseListInfo{
		Current:         page,
		PageSize:        pageSize,
		HasNextPage:     hasNextPage,
		HasPreviousPage: hasPreviousPage,
	}

	for _, v := range res.List {
		if v.SkuId != nil && *v.SkuId > 0 && v.Quantity != nil {
			c.Resp.List = append(c.Resp.List, &types.ShoppingCartItemInfo{
				Id:          v.Id,
				SkuId:       v.SkuId,
				ProductId:   v.ProductId,
				OrderId:     v.OrderId,
				RetailPrice: v.RetailPrice,
				Quantity:    v.Quantity,
				Status:      v.Status,
				Favorable:   v.Favorable,
				Prefetched:  v.Prefetched,
				Memo:        v.Memo,
				PostId:      v.PostId,
				InviterId:   v.InviterId,
			})
		}
	}

	return
}
